class AuthManager {
    constructor() {
        this.isLoggedIn = false;
        this.currentUser = null;
        this.guestTaskLimit = 3;
        // this.apiBaseUrl = 'http://yiye.localhost/api/v1';
        this.apiBaseUrl = 'https://www.ynaa.net/api/v1';
        this.verificationKey = null; // 存储验证码key
        this.init();
    }

    init() {
        console.log('[AuthManager] 初始化认证管理器...');

        // 使用 IPC 从主进程获取认证信息
        ipcRenderer.invoke('get-auth-token').then(token => {
            console.log('[AuthManager] 本地Token存在:', !!token);

            if (token) {
                console.log('[AuthManager] 发现token，设置为已登录状态');
                this.isLoggedIn = true;

                // 获取用户信息
                ipcRenderer.invoke('get-current-user').then(user => {
                    console.log('[AuthManager] 本地用户信息存在:', !!user);
                    if (user) {
                        console.log('[AuthManager] 恢复用户信息');
                        this.currentUser = user;
                    }

                    console.log('[AuthManager] 当前登录状态:', this.isLoggedIn);
                    this.setupLoginModal();
                    this.updateUIForAuthState();
                });
            } else {
                console.log('[AuthManager] 未找到token，保持未登录状态');
                this.isLoggedIn = false;
                this.currentUser = null;

                console.log('[AuthManager] 当前登录状态:', this.isLoggedIn);
                this.setupLoginModal();
                this.updateUIForAuthState();
            }
        });
    }

    setupLoginModal() {
        const loginModal = document.getElementById('loginModal');
        const loginClose = document.getElementById('loginClose');
        const loginTabs = document.querySelectorAll('.login-tab');
        const passwordForm = document.getElementById('passwordForm');
        const smsForm = document.getElementById('smsForm');
        const passwordLoginBtn = document.getElementById('passwordLoginBtn');
        const smsLoginBtn = document.getElementById('smsLoginBtn');
        const guestModeBtn = document.getElementById('guestModeBtn');
        const sendSmsBtn = document.getElementById('sendSmsBtn');
        const loginPrompt = document.getElementById('loginPrompt');
        const loginPromptHeader = document.getElementById('loginPromptHeader');
        const websiteLink = document.getElementById('websiteLink');
        const githubLink = document.getElementById('githubLink');
        const registerBtn = document.getElementById('registerBtn');
        const registerNew = document.querySelector('[data-action="registerNew"]');
        const noticeDismiss = document.getElementById('noticeDismiss');

        // 关闭登录模态框
        loginClose?.addEventListener('click', () => {
            this.hideLoginModal();
        });

        // 点击背景关闭
        loginModal?.addEventListener('click', (e) => {
            if (e.target === loginModal) {
                this.hideLoginModal();
            }
        });

        // 登录方式切换
        loginTabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabType = tab.dataset.tab;
                this.switchLoginTab(tabType);
            });
        });

        // 密码登录
        passwordLoginBtn?.addEventListener('click', () => {
            this.handlePasswordLogin();
        });

        // 验证码登录
        smsLoginBtn?.addEventListener('click', () => {
            this.handleSmsLogin();
        });

        // 游客模式
        guestModeBtn?.addEventListener('click', () => {
            this.enterGuestMode();
        });

        // 发送验证码
        sendSmsBtn?.addEventListener('click', () => {
            this.sendSmsCode();
        });

        // 登录提示点击
        loginPrompt?.addEventListener('click', (e) => {
            e.preventDefault();
            this.showLoginModal();
        });

        // 打开登录提示
        loginPromptHeader?.addEventListener('click', (e) => {
            e.preventDefault();
            this.showLoginModal();
        });

        registerNew?.addEventListener('click', (e) => {
            e.preventDefault();
            const { shell } = require('electron');
            shell.openExternal('https://www.ynaa.net/signup');
        });

        websiteLink?.addEventListener('click', (e) => {
            e.preventDefault();
            const { shell } = require('electron');
            shell.openExternal('https://www.ynaa.net/');
        });

        githubLink?.addEventListener('click', (e) => {
            e.preventDefault();
            const { shell } = require('electron');
            shell.openExternal('https://gitee.com/wongvio/todo-list');
        });

        // 注册
        registerBtn?.addEventListener('click', (e) => {
            e.preventDefault();
            const { shell } = require('electron');
            shell.openExternal('https://www.ynaa.net/signup');
        });

        // 关闭提示
        noticeDismiss?.addEventListener('click', () => {
            this.hideTaskLimitNotice();
        });
    }

    showLoginModal() {
        const loginModal = document.getElementById('loginModal');
        loginModal?.classList.add('show');
    }

    hideLoginModal() {
        const loginModal = document.getElementById('loginModal');
        loginModal?.classList.remove('show');
    }

    switchLoginTab(tabType) {
        const tabs = document.querySelectorAll('.login-tab');
        const passwordForm = document.getElementById('passwordForm');
        const smsForm = document.getElementById('smsForm');

        tabs.forEach(tab => {
            tab.classList.toggle('active', tab.dataset.tab === tabType);
        });

        if (tabType === 'password') {
            passwordForm?.classList.remove('hidden');
            smsForm?.classList.add('hidden');
        } else {
            passwordForm?.classList.add('hidden');
            smsForm?.classList.remove('hidden');
        }
    }

    async handlePasswordLogin() {
        const username = document.getElementById('username')?.value;
        const password = document.getElementById('password')?.value;
        const rememberMe = document.getElementById('rememberMe')?.checked;
        const loginBtn = document.getElementById('passwordLoginBtn');

        if (!username || !password) {
            window.notification.warning('请输入用户名和密码');
            return;
        }

        // 禁用登录按钮，防止重复提交
        loginBtn.disabled = true;
        loginBtn.textContent = '登录中...';

        try {
            const response = await fetch(`${this.apiBaseUrl}/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    account: username,
                    password: password
                })
            });

            const data = await response.json();

            if (data.success) {
                // 保存token到localStorage
                localStorage.setItem('authToken', data.data.token);
                localStorage.setItem('tokenType', data.data.token_type);

                // 打印保存后的结果
                console.log('[AuthManager] 保存的Token:', localStorage.getItem('authToken'));
                console.log('[AuthManager] 保存的TokenType:', localStorage.getItem('tokenType'));

                const user = {
                    id: data.data.user.id,
                    username: data.data.user.name,
                    email: data.data.user.email,
                    phone: data.data.user.phone
                };

                // 修改：默认保持登录状态，除非用户明确取消勾选
                this.loginSuccess(user, true);
            } else {
                window.notification.error(data.message || '登录失败');
            }
        } catch (error) {
            console.error('登录请求失败:', error);
            window.notification.error('网络错误，请检查网络连接');
        } finally {
            // 恢复登录按钮状态
            loginBtn.disabled = false;
            loginBtn.textContent = '登录';
        }
    }

    async handleSmsLogin() {
        const phoneNumber = document.getElementById('phoneNumber')?.value;
        const smsCode = document.getElementById('smsCode')?.value;
        const loginBtn = document.getElementById('smsLoginBtn');

        if (!phoneNumber || !smsCode) {
            window.notification.warning('请输入手机号和验证码');
            return;
        }

        if (!this.verificationKey) {
            window.notification.warning('请先获取验证码');
            return;
        }

        // 禁用登录按钮
        loginBtn.disabled = true;
        loginBtn.textContent = '登录中...';

        try {
            const response = await fetch(`${this.apiBaseUrl}/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    phone: phoneNumber,
                    verification_code: smsCode,
                    verification_key: this.verificationKey
                })
            });

            const data = await response.json();

            if (data.success) {
                // 保存token到localStorage
                localStorage.setItem('authToken', data.data.token);
                localStorage.setItem('tokenType', data.data.token_type);

                const user = {
                    id: data.data.user.id,
                    username: data.data.user.name,
                    email: data.data.user.email,
                    phone: data.data.user.phone
                };

                this.loginSuccess(user, true);
                // 清除验证码key
                this.verificationKey = null;
            } else {
                window.notification.error(data.message || '登录失败');
            }
        } catch (error) {
            console.error('登录请求失败:', error);
            window.notification.error('网络错误，请检查网络连接');
        } finally {
            // 恢复登录按钮状态
            loginBtn.disabled = false;
            loginBtn.textContent = '登录';
        }
    }

    async sendSmsCode() {
        const phoneNumber = document.getElementById('phoneNumber')?.value;
        const sendSmsBtn = document.getElementById('sendSmsBtn');

        if (!phoneNumber) {
            window.notification.warning('请先输入手机号');
            return;
        }

        // 验证手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(phoneNumber)) {
            window.notification.warning('请输入正确的手机号');
            return;
        }

        // 禁用发送按钮
        sendSmsBtn.disabled = true;
        sendSmsBtn.textContent = '发送中...';

        try {
            // 这里需要调用发送验证码的API接口
            const response = await fetch(`${this.apiBaseUrl}/send-sms`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    phone: phoneNumber
                })
            });

            const data = await response.json();

            if (data.success) {
                // 保存验证码key
                this.verificationKey = data.data.verification_key;

                // 开始倒计时
                let countdown = 60;
                const timer = setInterval(() => {
                    sendSmsBtn.textContent = `${countdown}秒后重发`;
                    countdown--;

                    if (countdown < 0) {
                        clearInterval(timer);
                        sendSmsBtn.disabled = false;
                        sendSmsBtn.textContent = '发送验证码';
                    }
                }, 1000);

                window.notification.success('验证码已发送，请查收');
            } else {
                window.notification.error(data.message || '发送验证码失败');
                sendSmsBtn.disabled = false;
                sendSmsBtn.textContent = '发送验证码';
            }
        } catch (error) {
            console.error('发送验证码失败:', error);
            window.notification.error('网络错误，请检查网络连接');
            sendSmsBtn.disabled = false;
            sendSmsBtn.textContent = '发送验证码';
        }
    }

    loginSuccess(user, rememberMe = true) {
        this.isLoggedIn = true;
        this.currentUser = user;

        // 使用 IPC 保存到主进程
        ipcRenderer.invoke('save-auth-token', localStorage.getItem('authToken'));
        ipcRenderer.invoke('save-token-type', localStorage.getItem('tokenType'));
        ipcRenderer.invoke('save-current-user', user);

        this.hideLoginModal();
        this.updateUIForAuthState();
        this.hideTaskLimitNotice();

        // 显示登录成功提示
        window.notification.success('登录成功！');
    }

    // 添加验证 token 有效性的方法
    // 添加验证 token 有效性的方法
    async validateToken() {
        console.log('[AuthManager] 开始验证token...');

        // 从 electron-store 获取 token
        const token = await ipcRenderer.invoke('get-auth-token');
        const tokenType = await ipcRenderer.invoke('get-token-type') || 'Bearer';

        console.log('[AuthManager] Token存在:', !!token);
        console.log('[AuthManager] Token类型:', tokenType);

        if (!token) {
            console.log('[AuthManager] 没有找到token，返回false');
            return false;
        }

        console.log('[AuthManager] Token前10位:', token.substring(0, 10) + '...');
        console.log('[AuthManager] 准备发送验证请求到:', `${this.apiBaseUrl}/user`);

        try {
            const response = await fetch(`${this.apiBaseUrl}/user`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Authorization': `${tokenType} ${token}`
                }
            });

            console.log('[AuthManager] 收到响应，状态码:', response.status);

            if (response.status === 401) {
                console.log('[AuthManager] Token无效(401)，清除登录状态');
                // 只有在401时才清除登录状态
                this.logout();
                return false;
            }

            if (response.ok) {
                console.log('[AuthManager] Token验证成功');
                const data = await response.json();
                console.log('[AuthManager] 用户数据:', data.data?.user?.name || '未知');
                
                // 保存token到localStorage
                console.log('[AuthManager] 正在保存token到localStorage...');
                localStorage.setItem('authToken', token);
                localStorage.setItem('tokenType', tokenType);
                console.log('[AuthManager] token保存成功:', token.substring(0, 10) + '...');
                console.log('[AuthManager] tokenType保存成功:', tokenType);

                if (data.data && data.data.user) {
                    this.currentUser = {
                        id: data.data.user.id,
                        username: data.data.user.name,
                        email: data.data.user.email,
                        phone: data.data.user.phone
                    };
                    // 更新用户信息到 electron-store
                    await ipcRenderer.invoke('save-current-user', this.currentUser);
                    console.log('[AuthManager] 用户信息已更新到 electron-store');
                }
                return true;
            }

            // 其他HTTP错误（非401）不清除登录状态，假设是临时问题
            console.warn('[AuthManager] Token验证失败，HTTP状态:', response.status, '保持登录状态');
            return true; // 保持登录状态，假设是临时网络问题
        } catch (error) {
            console.error('[AuthManager] Token验证网络错误:', error.message);
            console.log('[AuthManager] 网络错误，保持登录状态');
            // 网络错误不清除登录状态，保持离线可用
            return true; // 保持登录状态
        }
    }

    // 修改 logout 方法
    logout() {
        this.isLoggedIn = false;
        this.currentUser = null;

        // 清除本地 localStorage
        localStorage.removeItem('authToken');
        localStorage.removeItem('tokenType');
        localStorage.removeItem('currentUser');

        // 清除主进程存储
        ipcRenderer.invoke('clear-auth-data');

        this.updateUIForAuthState();
    }

    // 添加处理 401 错误的方法
    handle401Error() {
        this.logout();
        window.notification.warning('登录已过期，请重新登录');
        setTimeout(() => {
            this.showLoginModal();
        }, 1000);
    }

    enterGuestMode() {
        this.hideLoginModal();
        this.showTaskLimitNotice();
    }

    updateUIForAuthState() {
        const accountTrigger = document.getElementById('accountTrigger');
        const userNameSpan = accountTrigger?.querySelector('.user-name');
        const loggedInMenu = document.getElementById('loggedInMenu');
        const guestMenu = document.getElementById('guestMenu');
        const accountName = document.querySelector('#loggedInMenu .account-name');
        const accountEmail = document.querySelector('#loggedInMenu .account-email');

        // 设置页面中的账号状态元素
        const accountLoggedIn = document.getElementById('accountLoggedIn');
        const accountGuest = document.getElementById('accountGuest');

        if (this.isLoggedIn && this.currentUser) {
            // 显示已登录状态
            if (userNameSpan) userNameSpan.textContent = this.currentUser.username;
            if (accountName) accountName.textContent = this.currentUser.username;
            if (accountEmail) accountEmail.textContent = this.currentUser.email || this.currentUser.phone || '';

            // 显示登录菜单，隐藏游客菜单
            if (loggedInMenu) loggedInMenu.style.display = 'block';
            if (guestMenu) guestMenu.style.display = 'none';

            // 设置页面：显示已登录状态，隐藏游客状态
            if (accountLoggedIn) accountLoggedIn.style.display = 'block';
            if (accountGuest) accountGuest.style.display = 'none';

            // 更新设置页面中的用户信息
            const profileName = document.querySelector('.profile-name .setting-value');
            const profileEmail = document.querySelector('.profile-email .setting-value');
            if (profileName) profileName.textContent = this.currentUser.username;
            if (profileEmail) profileEmail.textContent = this.currentUser.email || this.currentUser.phone || '';
        } else {
            // 显示游客状态
            if (userNameSpan) userNameSpan.textContent = '游客模式';

            // 显示游客菜单，隐藏登录菜单
            if (loggedInMenu) loggedInMenu.style.display = 'none';
            if (guestMenu) guestMenu.style.display = 'block';

            // 设置页面：显示游客状态，隐藏已登录状态
            if (accountLoggedIn) accountLoggedIn.style.display = 'none';
            if (accountGuest) accountGuest.style.display = 'block';
        }
    }

    showTaskLimitNotice() {
        const notice = document.getElementById('taskLimitNotice');
        notice?.classList.add('show');
    }

    hideTaskLimitNotice() {
        const notice = document.getElementById('taskLimitNotice');
        notice?.classList.remove('show');
    }

    canAddTask(currentTaskCount) {
        if (this.isLoggedIn) {
            return true;
        }
        return currentTaskCount < this.guestTaskLimit;
    }

    getTaskLimitMessage() {
        return `游客模式最多只能创建${this.guestTaskLimit}条任务，请登录解锁更多功能。`;
    }

    // 检查是否需要显示登录提示
    checkTaskLimit(currentTaskCount) {
        if (!this.isLoggedIn && currentTaskCount >= this.guestTaskLimit) {
            this.showTaskLimitNotice();
            return false;
        }
        return true;
    }
}